<template>
    <view>
        <u-upload ref="upload" :accept="accept" :capture="capture" :compressed="compressed" :camera="camera"
            :maxDuration="maxDuration" :uploadIcon="uploadIcon" :uploadIconColor="uploadIconColor"
            :useBeforeRead="useBeforeRead" :previewFullImage="previewFullImage" :maxCount="maxCount"
            :disabled="readOnly ? true : disabled" :imageMode="imageMode" :name="name" :sizeType="sizeType" :multiple="multiple"
            :deletable="readOnly ? false : deletable" :maxSize="maxSize" :fileList="previeFileList" :uploadText="uploadText" :width="width"
            :height="height" :previewImage="previewImage" @afterRead="afterRead" @delete="clickDelete">
        </u-upload>
    </view>
</template>
<script>
    // 导入配置文件
    import config from '@/config';
    import { getToken } from '@/utils/auth';
    export default {
        name: "PyUploadImage",
        // 微信小程序解除样式隔离
        // #ifdef MP-WEIXIN
        options: {
            styleIsolation: "shared"
        },
        // #endif
        props: {
            // 新增属性开始
            // 上传的地址
            action: {
                type: String,
                default: config.baseUrl + "/common/upload"
            },
            // 上传时附带的额外参数
            data: Object,
            // 是否只读状态
            // 只读状态下deletable属性失效，一直为false
            // 只读状态下disable属性失效，一直设置为true
            readOnly: {
                type: Boolean,
                default: false
            },
            // 新增属性结束

            // u-upload原有属性开始
            // 接受的文件类型, 可选值为all media image file video
            // 最好只使用图片，对图片的支持很好
            accept: {
                type: String,
                default: uni.$u.props.upload.accept
            },
            // 	图片或视频拾取模式，当accept为image类型时设置capture可选额外camera可以直接调起摄像头
            capture: {
                type: [String, Array],
                default: uni.$u.props.upload.capture
            },
            // 当accept为video时生效，是否压缩视频，默认为true
            compressed: {
                type: Boolean,
                default: uni.$u.props.upload.compressed
            },
            // 当accept为video时生效，可选值为back或front
            camera: {
                type: String,
                default: uni.$u.props.upload.camera
            },
            // 当accept为video时生效，拍摄视频最长拍摄时间，单位秒
            maxDuration: {
                type: Number,
                default: uni.$u.props.upload.maxDuration
            },
            // 上传区域的图标，只能内置图标
            uploadIcon: {
                type: String,
                default: uni.$u.props.upload.uploadIcon
            },
            // 上传区域的图标的颜色，默认
            uploadIconColor: {
                type: String,
                default: uni.$u.props.upload.uploadIconColor
            },
            // 是否开启文件读取前事件
            useBeforeRead: {
                type: Boolean,
                default: uni.$u.props.upload.useBeforeRead
            },
            // 是否显示组件自带的图片预览功能
            previewFullImage: {
                type: Boolean,
                default: uni.$u.props.upload.previewFullImage
            },
            // 最大上传数量
            maxCount: {
                type: [String, Number],
                default: uni.$u.props.upload.maxCount
            },
            // 是否启用
            disabled: {
                type: Boolean,
                default: uni.$u.props.upload.disabled
            },
            // 预览上传的图片时的裁剪模式，和image组件mode属性一致
            imageMode: {
                type: String,
                default: uni.$u.props.upload.imageMode
            },
            // 标识符，可以在回调函数的第二项参数中获取
            name: {
                type: String,
                default: "file"
            },
            // 所选的图片的尺寸, 可选值为original compressed
            sizeType: {
                type: Array,
                default: uni.$u.props.upload.sizeType
            },
            // 是否开启图片多选，部分安卓机型不支持
            multiple: {
                type: Boolean,
                default: uni.$u.props.upload.multiple
            },
            // 是否展示删除按钮
            deletable: {
                type: Boolean,
                default: uni.$u.props.upload.deletable
            },
            // 文件大小限制，单位为byte
            maxSize: {
                type: [String, Number],
                default: uni.$u.props.upload.maxSize
            },
            // 显示已上传的文件列表
            fileList: {
                type: Array,
                default: uni.$u.props.upload.fileList
            },
            // 上传区域的提示文字
            uploadText: {
                type: String,
                default: uni.$u.props.upload.uploadText
            },
            // 内部预览图片区域和选择图片按钮的区域宽度
            width: {
                type: [String, Number],
                default: uni.$u.props.upload.width
            },
            // 内部预览图片区域和选择图片按钮的区域高度
            height: {
                type: [String, Number],
                default: uni.$u.props.upload.height
            },
            // 是否在上传完成后展示预览图
            previewImage: {
                type: Boolean,
                default: uni.$u.props.upload.previewImage
            }
        },
        data() {
            return {
                // 当前文件列表
                currentFileList: this.fileList,

                // 预览文件列表
                previeFileList: [],

                // 请求头
                header: {
                    Authorization: 'Bearer ' + getToken()
                }
            }
        },
        created() {
            // 如果有初始值，拼接后端前缀并显示图片
            let currentFileList = this.currentFileList;
            if (currentFileList.length > 0) {
                let baseUrl = config.baseUrl;
                currentFileList.forEach(currentFile => {
                    let url = baseUrl + currentFile;
                    this.previeFileList.push({ url });
                });

            }
        },
        watch: {
            fileList: function (newVal, oldVal) {
                // 表单重置时调用
                if (newVal.length == 0) {
                    this.previeFileList = [];
                }
            }
        },
        methods: {
            // 读取文件后处理函数
            afterRead(event) {
                let fileList = event.file;
                fileList.forEach(currentFile => {
                    // #ifdef H5
                    this.uploadFilePromise(currentFile.url).then(reponse => {
                        let data = JSON.parse(reponse);
                        if (data.code == 200) {
                            let filePath = data.fileName;
                            if (filePath) {
                                this.currentFileList.push(filePath);
                                this.previeFileList.push(currentFile);
                            }
                        } else {
                            this.$modal.msgError("上传文件失败");
                        }
                    })
                    // #endif

                    // #ifdef APP-PLUS || MP-WEIXIN
                    this.handleFilePath(currentFile.url).then(filePath => {
                        this.uploadFilePromise(filePath).then(response => {
                            let data = JSON.parse(response);
                            if (data.code === 200) {
                                this.currentFileList.push(data.fileName);

                                // 真机和微信小程序双向绑定不生效，将值传出
                                this.$emit("change", this.currentFileList);
                                this.previeFileList.push({ url: filePath });
                            } else {
                                this.$modal.msgError("上传文件失败");
                            }
                        });
                    })
                    // #endif
                });
            },

            // 处理文件路径，确保是微信小程序/安卓可用的本地路径
            handleFilePath(fileUrl) {
                return new Promise((resolve, reject) => {
                    if (fileUrl.startsWith("http")) {
                        resolve(fileUrl);
                    } else {
                        uni.saveFile({
                            tempFilePath: fileUrl,
                            success: res => resolve(res.savedFilePath)
                        });
                    }
                });
            },

            // 上传文件
            uploadFilePromise(fileUrl) {
                return new Promise((resolve, reject) => {
                    let url = this.action;
                    let name = this.name;
                    let formData = this.data;
                    let header = this.header;
                    let a = uni.uploadFile({
                        url, // 仅为示例，非真实的接口地址
                        filePath: fileUrl,
                        name,
                        formData,
                        header,
                        success: response => {
                            resolve(response.data);
                        },
                    });
                });
            },

            // 图片删除处理函数
            clickDelete(event) {
                let currentIndex = event.index;
                this.currentFileList.splice(currentIndex, 1);
                // #ifdef APP-PLUS || MP-WEIXIN
                // 真机和微信小程序双向绑定不生效，将值传出
                this.$emit("change", this.currentFileList);
                // #endif
                this.previeFileList.splice(currentIndex, 1);
            }
        },
    }
</script>
<style lang="css" scoped>
    /deep/ .u-upload__button--disabled {
       display: none;
    }
</style>